/**
 * useCallback
 *
 *    概念：
 *      缓存函数，配合memo去使用时才能有优化效果
 *
 *    语法：
 *      const newCallback = useCallback(callback, deep?)
 *        callback  - 需要被缓存的函数
 *        deep      - 依赖项数组
 *        newCallback - 已经处理好的函数
 *
 *    useCallback 可以用 useMemo 来替代
 *
 *      useCallback(callback, deep)  =>     useMemo(() => callback, deep)
 *
 *
 * 总结：
 *    1. PureComponent \ shouldComponentUpdate \ memo \ useMemo \ useCallback 都是处理优化的东西
 *
 */

import { memo, useCallback, useMemo, useState } from "react";
import useCount from "./hooks/useCount";

const Hello = memo(({ name, age, onChange }) => {
  console.log("Hello Render");
  return (
    <>
      <h4>
        Hello, {name}, {age}
      </h4>

      <button onClick={onChange}>触发父组件的 onChange</button>
    </>
  );
});

export default function App() {
  console.log("App Render");

  const [person, setPerson] = useState({ name: "张三", age: 18 });
  const { count, increment } = useCount();

  // const onChange = useCallback(() => {
  //   console.log("onChange", count);
  // }, []);

  const onChange = useMemo(() => {
    return () => {
      console.log("onChange", count);
    };
  }, []);

  return (
    <div>
      <h1>App</h1>

      <hr />
      <button onClick={() => increment()}>{count}</button>
      <button onClick={() => setPerson({ ...person, name: "里斯" })}>
        Name, {person.name}
      </button>
      <button onClick={() => setPerson({ ...person, age: 20 })}>
        Age, {person.age}
      </button>
      <hr />

      <Hello name={person.name} age={person.age} onChange={onChange} />
    </div>
  );
}
